package main

import (
  "encoding/json"
  "fmt"
  "io/ioutil"
  "log"
  "net/http"
  "rongyy-oss/helpers"
  "text/template"

  "github.com/joho/godotenv"
)

func main() {
  defer func() {
    if err := recover(); err != nil {
      fmt.Printf("%s\n", err)
    }
  }()

  err := godotenv.Load()
  if err != nil {
    log.Fatal(err)
    return
  }

  http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
    if r.Method != "POST" {
      w.Header().Add("Content-Type", "plan/text")
      htmlByte, err := ioutil.ReadFile("./templates/readme.html")
      if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
      }
      t, err := template.New("readme").Parse(string(htmlByte))
      if err != nil {
        fmt.Println("parse html文件失败,err", err)
        return
      }
      t.Execute(w, nil)
      return
    }

    formField := helpers.NewFormField(r)

    fieldName := formField.GetDefault("name", "file")
    bucketName := formField.GetDefault("bucket", "scszl")
    ossBaseRoot := formField.GetDefault("dir", "default")

    r.ParseMultipartForm(32 << 20)
    r.Body = http.MaxBytesReader(w, r.Body, 32<<20+512) //32.5Mb
    files := r.MultipartForm.File[fieldName]

    fileObjectKeys := make([]string, 0)

    for _, file := range files {
      localFile, err := helpers.NewUploader().UploadFile(file)
      if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
      }

      fileObjectKey, err := helpers.NewOss().Transmit(bucketName, ossBaseRoot, localFile)
      if err != nil {
        http.Error(w, err.Error(), http.StatusInternalServerError)
        return
      }
      fileObjectKeys = append(fileObjectKeys, fileObjectKey)
    }

    byteFileObjectKeys, err := json.Marshal(fileObjectKeys)
    if err != nil {
      http.Error(w, err.Error(), http.StatusInternalServerError)
      return
    }

    w.Write(byteFileObjectKeys)
  })

  http.ListenAndServe("127.0.0.1:8082", nil)
}
